/**
 * 事件
 * User: rendong
 * Date: 12-9-3
 * Time: 下午8:28
 * $Id: GEventDispatcher.js 9 2012-09-04 15:18:36Z rendong237@gmail.com $
 */

function GEventDispatcher(){
}

/**
 * 类私有属性
 * @type {Object}
 * @private
 */
GEventDispatcher.prototype._events = {};

// TODO: 存储全局的事件对应关系，加快事件触发

/**
 * 添加事件处理
 * @param type 事件类型，字符串
 * @param listener 事件处理函数，参数为：event
 * @param thisobj 回调函数的this环境对象
 */
GEventDispatcher.prototype.addEventListener = function(type, listener, thisobj){
    if (typeof listener != 'function')
        throw new Error("listener is not function! "+ typeof  listener);

    if (this._events[type] == null)
        this._events[type] = [];

    this._events[type].push([listener, thisobj]);
}

/**
 * 移除事件处理
 * @param type
 * @param listener
 */
GEventDispatcher.prototype.removeEventListener = function(type, listener, thisobj){
    var arr;

    arr = this._events[type];

    if (arr == null)
        return;

    for(var len=arr.length-1; len > -1; len--){
        if (arr[len][0] == listener){
            if (typeof arr[len][1] != 'undefined'){
                if (arr[len][1] == thisobj)
                    arr.splice(len, 1);
            }else{
                arr.splice(len, 1);
            }
        }
    }
}

/**
 * 触发事件
 * @param event {Event}
 */
GEventDispatcher.prototype.dispatchEvent = function(event){
    if (!event instanceof GEvent){
        throw new Error("event is not GEvent");
    }

    var arr = this._events[event.type];

    event.currentTarget = this;

    if (arr != null){
        for(var i=0; i<arr.length; i++){
            var method = arr[i][0];
            var thisobj = arr[i][1];
            method.call(thisobj, event);
        }
    }
}

/**
 * 根据事件类型，派发标准事件
 * @param type
 */
GEventDispatcher.prototype.dispatchEventByType = function(type){
    this.dispatchEvent(new GEvent(type));
}
